package com.guqj.thread.concurrent.syntool;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class CountDownLatchTest {

	public static void main(String[] args) {
		Videoconference videoconference = new Videoconference(9);
		Thread threadConference = new Thread(videoconference);
		threadConference.start();
		for (int i = 0; i < 10; i++) {
			Participant Participant = new Participant(videoconference, "Participant" + i);
			Thread th = new Thread(Participant);
			th.start();
		}
	}
}

class Videoconference implements Runnable {

	private CountDownLatch latch;

	public Videoconference(int num) {
		latch = new CountDownLatch(num);
	}

	public void arrive(String name) {
		System.out.println(name + " has arrived.");
		latch.countDown();
		System.out.println("VideoConference:Waiting for " + latch.getCount());
	}

	@Override
	public void run() {
		System.out.println("VideoConference:Initialization:" + latch.getCount());
		try {
			latch.await();
			System.out.printf("VideoConference: All the participants have come\n");
			System.out.printf("VideoConference: Let's start...\n");

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Participant implements Runnable {

	private Videoconference videoconference;
	private String name;

	public Participant(Videoconference videoconference, String name) {
		this.videoconference = videoconference;
		this.name = name;
	}

	@Override
	public void run() {
		long duration = (long) (Math.random() * 10);
		try {
			TimeUnit.SECONDS.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		videoconference.arrive(name);
	}
}